package com.loe.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zls on 2021/12/11
 */
public class VerifyEditText extends LinearLayout
{
    //默认密码明文显示时间为 200ms，之后密文显示
    private final static int DEFAULT_PASSWORD_VISIBLE_TIME = 200;

    private final List<TextView> mTextViewList = new ArrayList<>();
    private EditText mEditText;
    private Drawable drawableNormal, drawableSelected;
    private Context mContext;

    private int height = 32;
    private int count = 4;
    private int margin = 20;

    private float textSize = 16;
    private int textColor = 0xFF333333;

    //输入完成监听
    private InputChangeListener mInputChangeListener;

    public VerifyEditText(Context context)
    {
        this(context, null);
    }

    public VerifyEditText(Context context, @Nullable AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public VerifyEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs)
    {
        mContext = context;
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);
        @SuppressLint("CustomViewStyleable") TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.VerifyEditText);
        drawableNormal = obtainStyledAttributes.getDrawable(R.styleable.VerifyEditText_verify_background_normal);
        drawableSelected = obtainStyledAttributes.getDrawable(R.styleable.VerifyEditText_verify_background_selected);
        textColor = obtainStyledAttributes.getColor(R.styleable.VerifyEditText_verify_textColor, textColor);
        count = obtainStyledAttributes.getInt(R.styleable.VerifyEditText_verify_count, count);
        int inputType = obtainStyledAttributes.getInt(R.styleable.VerifyEditText_verify_inputType, InputType.TYPE_CLASS_NUMBER);
        final int passwordVisibleTime = obtainStyledAttributes.getInt(R.styleable.VerifyEditText_verify_password_visible_time, DEFAULT_PASSWORD_VISIBLE_TIME);
        height = (int) obtainStyledAttributes.getDimension(R.styleable.VerifyEditText_verify_height, px(height));
        margin = (int) obtainStyledAttributes.getDimension(R.styleable.VerifyEditText_verify_margin, px(margin));
        textSize = dp(obtainStyledAttributes.getDimension(R.styleable.VerifyEditText_verify_textSize, textSize));
        final boolean password = obtainStyledAttributes.getBoolean(R.styleable.VerifyEditText_verify_password, false);
        obtainStyledAttributes.recycle();
        if (count < 2)
        {
            count = 2;//最少 2 个 item
        }

        mEditText = new EditText(context);
        mEditText.setInputType(inputType);
        mEditText.setLayoutParams(new LayoutParams(1, 1));
        mEditText.setCursorVisible(false);
        mEditText.setBackground(null);
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});//限制输入长度为1
        mEditText.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                final TextView textView = mTextViewList.get(start);//获取对应的 textview
                if (before == 0)
                {//输入
                    CharSequence input = s.subSequence(start, s.length());//获取新输入的字
                    textView.setText(input);
                    if (password)
                    {//如果需要密文显示
                        textView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        //passwordVisibleTime 毫秒后设置为密文显示
                        textView.postDelayed(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                textView.setTransformationMethod(PasswordTransformationMethod.getInstance());
                            }
                        }, passwordVisibleTime);
                    }
                    setTextViewBackground(textView, drawableSelected);
                }
                else
                {//删除
                    textView.setText("");
                    setTextViewBackground(textView, drawableNormal);
                }
                if (mInputChangeListener != null)
                {
                    mInputChangeListener.onChange(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });
        addView(mEditText);
        //点击弹出软键盘
        setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                VerifyEditText.this.showSoftKeyBoard();
            }
        });

        measure();

    }

    private void measure()
    {
        //遍历生成 textView
        for (int i = 0; i < count; i++)
        {
            TextView textView = new TextView(mContext);
            textView.setTextSize(textSize);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(textColor);
//            textView.setTypeface(Typeface.DEFAULT_BOLD);
            LayoutParams layoutParams = new LayoutParams(0, height == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : height);
            layoutParams.weight = 1;
            if (i == 0)
            {
                layoutParams.leftMargin = -1;
            }
            else
            {
                layoutParams.leftMargin = margin;
            }
            textView.setLayoutParams(layoutParams);
            setTextViewBackground(textView, drawableNormal);
            addView(textView);
            mTextViewList.add(textView);
        }
    }

    /**
     * view 添加到窗口时，延迟 500ms 弹出软键盘
     */
    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        mEditText.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                showSoftKeyBoard();
            }
        }, 0);
    }

    /**
     * 设置背景
     *
     * @param textView
     * @param drawable
     */
    private void setTextViewBackground(TextView textView, Drawable drawable)
    {
        if (drawable != null)
        {
            textView.setBackground(drawable);
        }
    }

    /**
     * 获取当前输入的内容
     *
     * @return
     */
    public String getContent()
    {
        Editable text = mEditText.getText();
        if (TextUtils.isEmpty(text))
        {
            return "";
        }
        return mEditText.getText().toString();
    }

    /**
     * 清除内容
     */
    public void clearContent()
    {
        mEditText.setText("");
        for (int i = 0; i < mTextViewList.size(); i++)
        {
            TextView textView = mTextViewList.get(i);
            textView.setText("");
            setTextViewBackground(textView, drawableNormal);
        }
    }

    /**
     * 设置默认的内容
     *
     * @param content
     */
    public void setDefaultContent(String content)
    {
        mEditText.setText(content);
        mEditText.requestFocus();
        char[] chars = content.toCharArray();
        int min = Math.min(chars.length, mTextViewList.size());
        for (int i = 0; i < min; i++)
        {
            char aChar = chars[i];
            String s = String.valueOf(aChar);
            TextView textView = mTextViewList.get(i);
            textView.setText(s);
            setTextViewBackground(textView, drawableSelected);
        }
        if (mInputChangeListener != null)
        {
            mInputChangeListener.onChange(content.substring(0, min));
        }

    }

    /**
     * 显示软键盘
     */
    private void showSoftKeyBoard()
    {
        mEditText.requestFocus();
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 添加输入完成的监听
     *
     * @param inputCompleteListener
     */
    public void addInputCompleteListener(InputChangeListener inputCompleteListener)
    {
        mInputChangeListener = inputCompleteListener;
        Editable content = mEditText.getText();
        if (!TextUtils.isEmpty(content) && content.toString().length() == mTextViewList.size())
        {
            mInputChangeListener.onChange(content.toString());
        }
    }

    public interface InputChangeListener
    {
        void onChange(String content);
    }

    private int px(float dp)
    {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5);
    }

    public int dp(float px)
    {
        return (int) (px / Resources.getSystem().getDisplayMetrics().density + 0.5f);
    }
}